/* eslint-disable react-hooks/exhaustive-deps */
import React, { useContext } from 'react'
import ReactEcharts from 'echarts-for-react'
import { Row, Col, Empty } from 'antd';
import ProForm, { ProFormSelect } from '@ant-design/pro-form';
import styles from './index.less'
import ProList from '@ant-design/pro-list';
import ProCard from '@ant-design/pro-card';
import { useEffect } from 'react';
import { gamePaperUserList, getlistAnswerCount, getlistByItemId } from '@/services/gamePaperUser';
import { useState } from 'react';
import { getCourseListOption } from '@/services/student';
import { CourseContext } from '../../..';

import moment from 'moment';
import { baseUrl } from '@/utils/httpUrl';
import { TimeUtils } from '@/utils/timeUtils';
export default function Practice() {
  const ctx = useContext(CourseContext);
  const [opt, setOption] = useState<any>();

  const [data1, setData1] = useState<any>();
  const [data2, setData2] = useState<any>();
  const [data3, setData3] = useState<any>();
  const [data4, setData4] = useState<any>();
  const [data5, setData5] = useState<any>();
  const [show, setShow] = useState<boolean>(false);
  const [show1, setShow1] = useState<boolean>(false);
  const [list1, setOptionList] = useState<any>();
  useEffect(() => {
    (async () => {
      const res = await gamePaperUserList({ uid: ctx.uid, courseId: ctx.courseId })
      const res1 = res.result?.records?.map((item: any) => {
        return `${item.courseItemName}${item.stepName ? '-' : ''}${item.stepName || ''}`
      })
      setData1(res1)
      if (res1?.length > 0) {
        if (res1?.length > 3) {
          setShow(true)
        } else {
          setShow(false)
        }
      }
      const res2 = res.result?.records?.map((item: any) => {
        return (item?.firstRightPercent * 100).toFixed(2) ?? 0
      })
      setData2(res2)

      const res3 = res.result?.records?.map((item: any) => {
        return (item?.nowRightPercent * 100).toFixed(2) ?? 0
      })
      setData3(res3)

    })();
    (async () => {
      const res = await getlistAnswerCount({ uid: ctx.uid, courseId: ctx.courseId })
      const res4 = res?.result?.records?.map((item: any) => {
        return item.answerCount
      })
      setData4(res4)
      const res5 = res.result.records?.map((item: any) => {
        return `${item.courseItemName}${item.stepName ? '-' : ''}${item.stepName || ''}`
      })
      setData5(res5)
      if (res5?.length > 0) {
        if (res5?.length > 3) {
          setShow1(true)
        } else {
          setShow1(false)
        }
      }
    })();
    (async () => {
      const data = (await getCourseListOption({ uid: ctx.uid, stepType: 4, courseId: ctx.courseId, pageSize: -1, isUnlock: 1 }))?.result?.records;
      const list = data?.map((item: any) => {
        return { label: `${item.name}(${moment(item.startTime).format('YYYY.MM.DD')})`, value: item.id }
      })
      if (opt == null) {
        setOption(list?.[list?.length - 1]?.value);
      }
      setOptionList(list)
    })()
  }, [ctx])
  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      orient: 'horization',
      x: 'right',
      y: 'center',
      data: ['首次正确率', '当前正确率']
    },
    grid: {
      right: '120',
    },
    xAxis: {
      type: 'category',
      data: data1,
      axisTick: {
        alignWithLabel: true,
        show: false
      },
      axisLabel: {
        interval: 0,
        rotate: -20,
        top: 5,
        textStyle: {
          color: '#000',
          fontSize: 10,

        }
      },
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLine: {
        show: true,
      },
      splitNumber: 10,
      minInterval: 1,
    },
    dataZoom: [
      {
        type: 'slider',
        realtime: true,
        start: 0,
        end: Math.floor(100 / (data1?.length / 3)),  // 数据窗口范围的结束百分比。范围是：0 ~ 100。
        height: 5, //组件高度
        // left: 5, //左边的距离
        // right: 5, //右边的距离
        bottom: 10, //下边的距离
        show: show,  // 是否展示
        fillerColor: "rgba(17, 100, 210, 0.42)", // 滚动条颜色
        borderColor: "rgba(17, 100, 210, 0.12)",
        handleSize: 0,      //两边手柄尺寸
        showDetail: false, //拖拽时是否展示滚动条两侧的文字
        zoomLock: true,         //是否只平移不缩放
        moveOnMouseMove: false //鼠标移动能触发数据窗口平移
        //zoomOnMouseWheel: false, //鼠标移动能触发数据窗口缩放
      },
      {
        type: 'inside', // 内置在坐标系中
        start: 0, // 数据窗口范围的起始百分比。范围是：0 ~ 100。表示 0% ~ 100%。
        end: Math.floor(100 / (data1?.length / 3)), // 数据窗口范围的结束百分比。范围是：0 ~ 100。
        zoomOnMouseWheel: false,  // 关闭滚轮缩放
        moveOnMouseWheel: true, // 开启滚轮平移
        moveOnMouseMove: true  // 鼠标移动能触发数据窗口平移
      }
    ],
    series: [
      {
        name: '首次正确率',
        type: 'line',
        symbolSize: 10,
        symbol: 'circle',
        itemStyle: {
          normal: {
            color: "#ff5e5c",
            lineStyle: {
              color: "#ff5e5c"
            }, label: {
              show: true
            }
          }
        },
        data: data2
      },
      {
        name: '当前正确率',
        type: 'line',
        symbolSize: 10,
        symbol: 'circle',
        itemStyle: {
          normal: {
            color: "#ff9d50",
            lineStyle: {
              color: "#ff9d50"
            }, label: {
              show: true
            }
          }
        },
        data: data3
      },

    ]
  }
  const option1 = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      orient: 'horization',
      x: 'right',
      y: 'center',
      data: ['答题次数']
    },
    grid: {
      right: '120',
    },
    xAxis: {
      type: 'category',
      data: data5,
      axisTick: {
        alignWithLabel: true,
        show: false
      },
      axisLabel: {
        interval: 0,
        rotate: -20,
        top: 5,
        textStyle: {
          color: '#000',
          fontSize: 10,

        }
      },
    },
    yAxis: {
      type: 'value',
      max: 10,
      axisLine: {
        show: true,
      },
      splitNumber: 10,
      minInterval: 1,
    },
    dataZoom: [
      {
        type: 'slider',
        realtime: true,
        start: 0,
        end: Math.floor(100 / (data5?.length / 3)),  // 数据窗口范围的结束百分比。范围是：0 ~ 100。
        height: 5, //组件高度
        // left: 5, //左边的距离
        // right: 5, //右边的距离
        bottom: 10, //下边的距离
        show: show1,  // 是否展示
        fillerColor: "rgba(17, 100, 210, 0.42)", // 滚动条颜色
        borderColor: "rgba(17, 100, 210, 0.12)",
        handleSize: 0,      //两边手柄尺寸
        showDetail: false, //拖拽时是否展示滚动条两侧的文字
        zoomLock: true,         //是否只平移不缩放
        moveOnMouseMove: false //鼠标移动能触发数据窗口平移
        //zoomOnMouseWheel: false, //鼠标移动能触发数据窗口缩放
      },
      {
        type: 'inside', // 内置在坐标系中
        start: 0, // 数据窗口范围的起始百分比。范围是：0 ~ 100。表示 0% ~ 100%。
        end: Math.floor(100 / (data5?.length / 3)), // 数据窗口范围的结束百分比。范围是：0 ~ 100。
        zoomOnMouseWheel: false,  // 关闭滚轮缩放
        moveOnMouseWheel: true, // 开启滚轮平移
        moveOnMouseMove: true  // 鼠标移动能触发数据窗口平移
      }
    ],
    series: [
      {
        name: '答题次数',
        type: 'line',
        symbolSize: 10,
        symbol: 'circle',
        itemStyle: {
          normal: {
            color: "#ff5e5c",
            lineStyle: {
              color: "#ff5e5c"
            },
            label: {
              show: true
            }
          }
        },
        data: data4
      },
    ]
  }
  const goSeeClass = (paperId: any) => {
    const w = window.open('_black');
    w!.location.href = `${baseUrl.http?.replace('/api', '')}/gogame/?scene=course_test&stepId=${paperId}`
  }
  return (
    <div>
      {
        data1?.length !== 0 || data2?.length !== 0 ?
          <ReactEcharts notMerge option={option} /> :
          <Empty description={'还没有已解锁的练习题'} image={Empty.PRESENTED_IMAGE_SIMPLE} />
      }
      {
        data4?.length !== 0 ?
          <ReactEcharts notMerge option={option1} /> :
          <Empty description={'还没有已解锁的练习题'} image={Empty.PRESENTED_IMAGE_SIMPLE} />
      }

      {
        list1 && list1.length !== 0 ?
          <div style={{ textAlign: 'left' }}>
            <Row className={styles.right_pro_form_style}>
              <Col span={18}>
                <ProForm
                  style={{ width: "70%", float: 'right' }}
                  layout="horizontal"
                  colon={true}
                  labelAlign='right'
                >
                  <ProFormSelect
                    colProps={{ xl: 8, md: 12 }}
                    label="选择条目"
                    name="required"
                    fieldProps={{
                      onChange: (val) => setOption(val),
                      value: opt,
                      allowClear: false
                    }}
                    options={list1}
                  />
                </ProForm>
              </Col>
            </Row>
          </div> : null
      }


      <div className={styles.test_paper}>
        {opt == null ? null : <ProList<any>
          rowKey="id"
          itemLayout="horizontal"
          params={{
            uid: ctx.uid,
            courseId: ctx.courseId,
            itemId: opt
          }}
          request={async (params) => {
            const res = await getlistByItemId({ ...params })
            return {
              data: res.result.records
            }
          }}
          grid={{ gutter: 16, column: 2 }}
          renderItem={(item: any) => (
            <ProCard className={styles.card_item} >
              <ProCard style={{ background: '#f2f2f2' }}>
                <div style={{ padding: '0 17px 15px' }}>

                  <div className={styles.item} style={{ fontSize: '16px' }}>{item.stepName}</div>
                  <div style={{ textAlign: 'left' }}>
                    <div className={styles.item}>答题次数：{item.answerCount}</div>
                    <div className={styles.item}>平均答题时间：{TimeUtils.handlerTime(item.avgAnswerTime)}</div>
                    <div className={styles.item}>首次答题正确率：{(item.firstRightPercent * 100).toFixed(0)}%</div>
                    <div className={styles.item}>当前答题正确率：{(item.nowRightPercent * 100).toFixed(0)}%</div>
                  </div>
                  <a className={styles.item} onClick={() => goSeeClass(item?.id)}>查看试卷</a>
                </div>
              </ProCard>
            </ProCard>
          )}
        />}
      </div>

    </div>
  )
}
